package com.central.apps.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.app.service.HandlerService;
import com.central.apps.dao.BlMessageDao;
import com.central.apps.entity.BlMessage;
import com.central.apps.service.MessageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 消息服务impl
 *
 * @author JHY
 * @date 2022/10/31
 */
@Service
public class MessageServiceImpl extends ServiceImpl<BlMessageDao, BlMessage> implements MessageService {
    @Resource
    private BlMessageDao dao;
    @Autowired
    private HandlerService handlerService;

    @Override
    public int addMessage(BlMessage message) {
        String recipientselect = message.getRecipientselect();
        if (StringUtils.isEmpty(recipientselect) || "接收人".equals(recipientselect)) {
            if (message.getCreatetime() == null) {
                message.setCreatetime(new Date());
            }
            return dao.insert(message);
        } else {
            // 接收角色
            String rolecode = message.getRolecode();
            List<Map<String, Object>> rolesList =
                    handlerService
                            .findBySql("SELECT u.* FROM sys_user u LEFT JOIN sys_role_user sru ON u.worknumber = sru.userworknumber WHERE sru.rolecode = '" + rolecode + "'");
            if (rolesList.size() > 0) {
                Date date = new Date();
                for (Map<String, Object> item : rolesList) {
                    String id = MapUtil.getStr(item, "id");
                    String nickname = MapUtil.getStr(item, "nickname");
                    BlMessage insMsg = new BlMessage();
                    insMsg.setCreatetime(date);
                    insMsg.setIsshow(message.getIsshow());
                    insMsg.setContent(message.getContent());
                    insMsg.setTitle(message.getTitle());
                    insMsg.setMessagenum(message.getMessagenum());
                    insMsg.setCreateuser(message.getCreateuser());
                    insMsg.setCreateuserdesc(message.getCreateuserdesc());
                    insMsg.setStatus(message.getStatus());
                    insMsg.setRoleid(message.getRoleid());
                    insMsg.setRolecode(rolecode);
                    insMsg.setRolename(message.getRolename());
                    insMsg.setRoledeptname(message.getRoledeptname());
                    insMsg.setVersion(message.getVersion());
                    insMsg.setRecipient(id);
                    insMsg.setRecipientname(nickname);
                    dao.insert(insMsg);
                }
            }
            return 1;
        }

    }
}
